<!--
 * @Author: master
 * @Date: 2022-06-07 09:25:07
 * @LastEditors: master
 * @LastEditTime: 2023-06-05 19:29:05
 * @Description: 大屏组件，大屏适配器
-->
<template>
  <div class="screen-adapter" :style="style">
    <slot />
  </div>
</template>
<script>
import { debounce } from '@path/common/tool/units.js';
/**
 * 浏览器窗口监听
 */
const addWindowResize = func => {
  window.addEventListener('resize', func, true);
};
/**
 * 删除浏览器窗口监听
 */
const removeWindowResize = func => {
  window.removeEventListener('resize', func, true);
};
export default {
  props: {
    width: {
      default: 1920,
      type: Number,
    },
    height: {
      default: 1080,
      type: Number,
    },
  },
  data() {
    return {
      style: {
        width: `${this.width}px`,
        height: `${this.height}px`,
        transform: 'scale(1) translate(-50%, -50%)',
      },
    };
  },
  watch: {
    width: function () {
      this.style = {
        width: `${this.width}px`,
        height: `${this.height}px`,
        transform: 'scale(1) translate(-50%, -50%)',
      };
      // 设置缩放比例
      this.setScale();
    },
    height: function () {
      this.style = {
        width: `${this.width}px`,
        height: `${this.height}px`,
        transform: 'scale(1) translate(-50%, -50%)',
      };
      // 设置缩放比例
      this.setScale();
    },
  },
  mounted() {
    // 设置缩放比例
    this.setScale();
    // 初始化
    this.init();
  },
  methods: {
    /**
     * 初始化
     */
    init() {
      // 添加防抖
      this.resize = debounce(this.setScale, 1000);
      // 监听窗口变化事件
      addWindowResize(this.resize);
    },
    /**
     * 获取当前需要自适应的缩放比例
     */
    getScale() {
      const w = window.innerWidth / this.width;
      const h = window.innerHeight / this.height;
      return w < h ? w : h;
    },
    /**
     * 设置缩放比例
     */
    setScale() {
      this.style.transform = 'scale(' + this.getScale() + ') translate(-50%, -50%)';
    },
  },
  destroyed() {
    // 事件取消
    removeWindowResize(this.resize);
  },
};
</script>
<style lang="less" scoped>
.screen-adapter {
  position: absolute;
  top: 50%;
  left: 50%;
  background-size: 100% 100%;
  transform-origin: 0 0;
  transition: 0.3s;
}
</style>
